package org.study.swing.study01.table;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import lombok.*;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.Serializable;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 作用描述
 * 参考 https://blog.csdn.net/zpwangshisuifeng/article/details/74937312
 *
 * @author doveylovey
 * @version v1.0.0
 * @email 1135782208@qq.com
 * @date 2024年11月12日
 */
public class TablePageDemo01 extends JFrame {
    public static void main(String[] args) {
        new TablePageDemo01();
    }

    @Getter
    @Setter
    private int lastPage;
    @Getter
    @Setter
    private int currentPage = 1;
    @Getter
    @Setter
    private int pageSize = 7;
    JTable table = null;
    DefaultTableModel defaultTableModel = null;

    static List<User> userList = new ArrayList<>() {{
        LocalDateTime localDateTime = LocalDateTime.now();
        this.add(new User(IdUtil.getSnowflakeNextId(), "用户-01", RandomUtil.randomBoolean(), "028-12345601", "02812345601@qq.com", localDateTime.toLocalDate().minusMonths(RandomUtil.randomInt(10, 100)), localDateTime));
        this.add(new User(IdUtil.getSnowflakeNextId(), "用户-02", RandomUtil.randomBoolean(), "028-12345602", "02812345602@qq.com", localDateTime.toLocalDate().minusMonths(RandomUtil.randomInt(10, 100)), localDateTime));
        this.add(new User(IdUtil.getSnowflakeNextId(), "用户-03", RandomUtil.randomBoolean(), "028-12345603", "02812345603@qq.com", localDateTime.toLocalDate().minusMonths(RandomUtil.randomInt(10, 100)), localDateTime));
        this.add(new User(IdUtil.getSnowflakeNextId(), "用户-04", RandomUtil.randomBoolean(), "028-12345604", "02812345604@qq.com", localDateTime.toLocalDate().minusMonths(RandomUtil.randomInt(10, 100)), localDateTime));
        this.add(new User(IdUtil.getSnowflakeNextId(), "用户-05", RandomUtil.randomBoolean(), "028-12345605", "02812345605@qq.com", localDateTime.toLocalDate().minusMonths(RandomUtil.randomInt(10, 100)), localDateTime));
        this.add(new User(IdUtil.getSnowflakeNextId(), "用户-06", RandomUtil.randomBoolean(), "028-12345606", "02812345606@qq.com", localDateTime.toLocalDate().minusMonths(RandomUtil.randomInt(10, 100)), localDateTime));
        this.add(new User(IdUtil.getSnowflakeNextId(), "用户-07", RandomUtil.randomBoolean(), "028-12345607", "02812345607@qq.com", localDateTime.toLocalDate().minusMonths(RandomUtil.randomInt(10, 100)), localDateTime));
        this.add(new User(IdUtil.getSnowflakeNextId(), "用户-08", RandomUtil.randomBoolean(), "028-12345608", "02812345608@qq.com", localDateTime.toLocalDate().minusMonths(RandomUtil.randomInt(10, 100)), localDateTime));
        this.add(new User(IdUtil.getSnowflakeNextId(), "用户-09", RandomUtil.randomBoolean(), "028-12345609", "02812345609@qq.com", localDateTime.toLocalDate().minusMonths(RandomUtil.randomInt(10, 100)), localDateTime));
        this.add(new User(IdUtil.getSnowflakeNextId(), "用户-10", RandomUtil.randomBoolean(), "028-12345610", "02812345610@qq.com", localDateTime.toLocalDate().minusMonths(RandomUtil.randomInt(10, 100)), localDateTime));
        this.add(new User(IdUtil.getSnowflakeNextId(), "用户-11", RandomUtil.randomBoolean(), "028-12345611", "02812345611@qq.com", localDateTime.toLocalDate().minusMonths(RandomUtil.randomInt(10, 100)), localDateTime));
        this.add(new User(IdUtil.getSnowflakeNextId(), "用户-12", RandomUtil.randomBoolean(), "028-12345612", "02812345612@qq.com", localDateTime.toLocalDate().minusMonths(RandomUtil.randomInt(10, 100)), localDateTime));
        this.add(new User(IdUtil.getSnowflakeNextId(), "用户-13", RandomUtil.randomBoolean(), "028-12345613", "02812345613@qq.com", localDateTime.toLocalDate().minusMonths(RandomUtil.randomInt(10, 100)), localDateTime));
        this.add(new User(IdUtil.getSnowflakeNextId(), "用户-14", RandomUtil.randomBoolean(), "028-12345614", "02812345614@qq.com", localDateTime.toLocalDate().minusMonths(RandomUtil.randomInt(10, 100)), localDateTime));
        this.add(new User(IdUtil.getSnowflakeNextId(), "用户-15", RandomUtil.randomBoolean(), "028-12345615", "02812345615@qq.com", localDateTime.toLocalDate().minusMonths(RandomUtil.randomInt(10, 100)), localDateTime));
    }};

    public TablePageDemo01() {
        if (userList.size() % pageSize == 0) {
            setLastPage(userList.size() / getPageSize());
        } else {
            setLastPage(userList.size() / getPageSize() + 1);
        }

        String[] columnNames = {"用户ID", "用户名", "性别", "联系电话", "电子邮箱", "出生日期", "创建时间", "备注"};
        defaultTableModel = new DefaultTableModel(columnNames, 0);

        table = new JTable(defaultTableModel);
        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setViewportView(table);
        super.getContentPane().add(scrollPane);

        super.setTitle("Java Swing 表格分页示例");
        super.setBounds(100, 100, 1000, 400);
        // 将窗口居中显示在屏幕上
        super.setLocationRelativeTo(null);
        super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        this.showTable(currentPage);

        JPanel panel = new JPanel();
        super.getContentPane().add(panel, BorderLayout.SOUTH);

        JButton button = new JButton("首页");
        button.addActionListener(new MyTable());
        button.setActionCommand("首页");
        panel.add(button);

        JButton button1 = new JButton("上一页");
        button1.addActionListener(new MyTable());
        panel.add(button1);

        JButton button2 = new JButton("下一页");
        button2.addActionListener(new MyTable());
        panel.add(button2);

        JButton button3 = new JButton("末页");
        button3.addActionListener(new MyTable());
        panel.add(button3);

        super.setVisible(true);
    }

    public void showTable(int currentPage) {
        // 清除原有行
        defaultTableModel.setRowCount(0);
        this.setCurrentPage(currentPage);
        List<User> pageList = this.findUsers(currentPage, pageSize);
        // 获得数据
        pageList.forEach(user -> {
            String sexStr = "未知";
            if (user.getSex() != null) {
                if (user.getSex()) {
                    sexStr = "哥们儿";
                } else {
                    sexStr = "妹子";
                }
            }
            String gmtCreateStr = null;
            if (user.getGmtCreate() != null) {
                gmtCreateStr = DateUtil.format(user.getGmtCreate(), "yyyy-MM-dd HH:mm:ss");
            }
            // 添加数据：方式一
            /*Vector rowData = new Vector();
            rowData.add(user.getId());
            rowData.add(user.getName());
            rowData.add(sexStr);
            rowData.add(user.getPhone());
            rowData.add(user.getEmail());
            rowData.add(user.getBirthday());
            rowData.add(gmtCreateStr);
            defaultTableModel.addRow(rowData);*/
            // 添加数据：方式二
            defaultTableModel.addRow(new Object[]{user.getId(), user.getName(), sexStr, user.getPhone(), user.getEmail(), user.getBirthday(), gmtCreateStr});
        });

        // 表格列的自动调整
        // table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        // 单选
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        table.setSelectionBackground(Color.YELLOW);
        table.setSelectionForeground(Color.RED);
        table.setRowHeight(30);
    }

    class MyTable implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            if ("首页".equals(e.getActionCommand())) {
                showTable(1);
            }
            if ("上一页".equals(e.getActionCommand())) {
                if (getCurrentPage() <= 1) {
                    setCurrentPage(2);
                }
                showTable(getCurrentPage() - 1);
            }
            if ("下一页".equals(e.getActionCommand())) {
                if (getCurrentPage() < getLastPage()) {
                    showTable(getCurrentPage() + 1);
                } else {
                    showTable(getLastPage());
                }
            }
            if ("末页".equals(e.getActionCommand())) {
                showTable(getLastPage());
            }
        }
    }

    public List<User> findUsers(int currentPage, int pageSize) {
        int listLength = userList.size();
        if (currentPage < 1) {
            currentPage = 1;
        }
        int startIndex = (currentPage - 1) * pageSize;
        int endIndex = startIndex + pageSize;

        if (endIndex >= listLength) {
            endIndex = listLength;
        }
        java.util.List<User> resultList = userList.subList(startIndex, endIndex);
        return resultList;
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    static class User implements Serializable {
        private static final long serialVersionUID = 1L;

        private Long id;
        private String name;
        private Boolean sex;
        private String phone;
        private String email;
        private LocalDate birthday;
        private LocalDateTime gmtCreate;
    }
}
